﻿<script src="/Scripts/jquery-1.8.2.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>

<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>

<script src="/Scripts/jquery.unobtrusive-ajax.min.js"></script>
@using (Html.BeginForm("Upload", "Product", FormMethod.Post, new { enctype = "multipart/form-data", @id = "formUpload" }))
{   
    <input id="imgInp" type="file" name="files" multiple="multiple" onchange="submitForm()"><br>
}
<div id="review"></div>
<script type="text/javascript">
    function submitForm() {
        $("#formUpload").submit();
    }
    $(function () {
        $("#formUpload").submit(function (event) {
            var dataString;
            event.preventDefault();
            var action = $("#formUpload").attr("action");
            if ($("#formUpload").attr("enctype") == "multipart/form-data") {
                //this only works in some browsers.
                //purpose? to submit files over ajax. because screw iframes.
                //also, we need to call .get(0) on the jQuery element to turn it into a regular DOM element so that FormData can use it.
                dataString = new FormData($("#formUpload").get(0));
            } else {
                // regular form, do your own thing if you need it
            }
            $.ajax({
                type: "POST",
                url: action,
                data: dataString,
                dataType: "json", //change to your own, else read my note above on enabling the JsonValueProviderFactory in MVC
                contentType: false,
                processData: false,
                beforeSend: function () {
                    $("#review").html('');
                },
                success: function (data) {
                    //BTW, data is one of the worst names you can make for a variable
                    for (var i = 0; i < data.length; i++) {
                        $("#review").append('<img style="width: 80px;height: 100px" src="../../Files/' + data[i] + '"/>');
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    //do your own thing
                    alert(jqXHR + textStatus + errorThrown);
                }
            });
        }); //end .submit()
    });
</script>
